import http
import json
from django.contrib.auth import login, authenticate
from django.http import JsonResponse
from django.views import View

from celery_tasks.qiniuyun.qiniu_storage import storage
from ihome.settings.settings import URL
from ihome.utils.views import LoginRequiredMixin
from mod.models import BaseModel, Area, House, User, Order, HouseImage

'''登录接口'''
#　　Json　　参数：mobile,password
class LoginView(View):

    def post(self,request):

        json_dict  = json.loads(request.body.decode())
        mobile = json_dict['mobile']
        password = json_dict['password']

        if not all([mobile,password]):
            return JsonResponse({
                 "errno": "0",
                 "errmsg": "登录成功"
            })
        #　账号认证
        user = authenticate(username=mobile,
                            password=password)
        if user is None:
            return JsonResponse({
                "errno": "4104",
                "errmsg": "用户不存在或未激活"
            })
        login(request,user)

        response = JsonResponse({
                 "errno": "0",
                 "errmsg": "登录成功"
            })
        #用户登录和注册的时候, 都需要把用户的信息写入到cookie.
        response.set_cookie('mobile',mobile,3600*24*14)

        return response


# '''个人中心'''
# from celery_tasks.qiniuyun.qiniu_storage import storage
# class UserInfoView(LoginRequiredMixin,View):
#     def get(self,request):
#         user = request.user
        # avatar=request.FILES.get('avatar')
        # key = storage(avatar.read())
        # print(key)
        # area = Area.objects.get(id=request.user.id)
        # create_time = area.create_time
        # data = {
        #     'avatar':URL + '/' + key,
        #     'name':request.user.username,
        #     'mobile':request.user.mobile,
        #     'id':request.user.id,
        #     'create_time':create_time,
        # }
        # response = JsonResponse({
        #     "data": data,
        #     "errmsg": "OK",
        #     "errno": "0"
        # })
        #
        # return response


# '''上传个人头像（七牛云）'''
# class UploadsPesonal(LoginRequiredMixin,View):
#     def post(self,request):
#
#         user = request.user
#         #  file文件类型（二进制）
#         avatar = request.FILES.get('avatar')
#         key = storage(avatar.read())
#         data = {}
#         # 拼接路由
#         data['avatar_url'] = URL + '/' + key
#
#         return JsonResponse({
#             "data": data,
#             "errmsg": "头像上传成功",
#             "errno": "0"
#         })


'''发布房源'''
class ReleaseHousingStock(LoginRequiredMixin,View):
    pass


# '''上传房源图片'''
# class UploadHousePicture(View):
#     def post(self,request):
#         #  file文件类型（二进制）
#         house_image = request.FILES.get('house_image')
#         key = storage(house_image.read())
#         data = {}
#         # 拼接路由
#         data['url'] = URL + '/' + key
#
#         return JsonResponse({
#             "data": data,
#             "errmsg": "图片上传成功",
#             "errno": "0"
#         })


'''我的房屋列表'''
class MyHouseList(View):
    def get(self, request):
        # avatar = request.FILES.get('avatar')
        # key = storage(avatar.read())
        #
        # # 拼接路由
        # avatar_url = URL + '/' + key

        user = request.user
        try:
            houses = House.objects.filter(user_id=user.id)

        except Exception as e:
            return JsonResponse({
                "errmsg": "获取数据失败",
                "errno": "4002"
            })
        list = []
        for house in houses:
            try:
                # area = Area.objects.get(name=house.area)
                area = Area.objects.get(id=house.area_id)
                print(house.id)

            except Exception as e:
                return JsonResponse({
                    "errmsg": "获取数据失败",
                    "errno": "4002"})

            # house_image = HouseImage.objects.get(house_id=house.id)
            list.append({
                "address": area.id,
                "area_name": area.name,
                "ctime": house.create_time.strftime("%Y-%m-%d"),
                "house_id": house.id,
                "img_url": "",
                "order_count": house.order_count,
                "price": house.price,
                "room_count": house.room_count,
                "title": house.title,
                'user_avatar': str(user.avatar)
            })

        data = {}
        data['houses'] = list

        return JsonResponse({
            "data": data,
            "errmsg": "OK",
            "errno": "0"
        })

    def post(self,request):
        json_dict = json.loads(request.body.decode())
        title = json_dict['title']
        area_id = json_dict['area_id']
        address = json_dict['address']
        room_count= json_dict['room_count']
        acreage = json_dict['acreage']
        unit = json_dict['unit']
        capacity = json_dict['capacity']
        beds = json_dict['beds']
        deposit = json_dict['deposit']
        min_days = json_dict['min_days']
        max_days= json_dict['max_days']
        facility = json_dict['facility']
        try:
            house = House.objects.create(
            user = request.user,
            title =title,
            area_id = area_id,
            address = address,
            room_count= room_count,
            acreage = acreage,
            unit = unit,
            capacity = capacity,
            beds = beds,
            deposit = int(deposit),
            min_days = min_days,
            max_days= max_days,
            facility = facility
            )
        except Exception as e:
            return JsonResponse({
                "errmsg": "获取数据失败",
                "errno": "4002"
            })
        return JsonResponse({
            "data": {'house_id':house.id},
            "errmsg": "发布成功",
            "errno": "0"
        })


'''房源详情页面'''
class HouseInfo(View):
    def get(self,request,house_id):
        #  需要分用户是否登录，分析
        # user_id	int	当前登录用户的用户id，如果没有登录，则为 -1
        # house  dict  房屋详细信息
        # avatar = request.FILES.get('avatar')
        # key = storage(avatar.read())
        # # 拼接路由
        # avatar_url = URL + '/' + key
        print(house_id)
        user = request.user
        try:
            house = House.objects.get(id=house_id)

        except Exception as e:
            return JsonResponse({
                "errmsg": "获取数据失败",
                "errno": "4002"
            })

        try:
            house_images = HouseImage.objects.filter(house_id=house.id)
        except Exception as e:
            house_images = []

        order = Order.objects.get(house_id=house_id)

        date_joined = request.user.date_joined
        print(type(date_joined))
        ctime = date_joined.strftime("%Y-%m-%d %H:%M:%S")
        url_list = []
        if house_images:
            for house_image in house_images:
                url_list.append(house_image.url)
        data = {
            "house": {
            "acreage": house.acreage,
            "address": house.address,
            "beds": house.beds,
            "capacity": house.capacity,
            "comments": [{
                "comment": order.comment,
                "ctime": ctime,
                "user_name": "匿名用户"
            }],
            "deposit": house.deposit,
            "facilities": house.facility,
            "hid": 4,
            "img_urls": url_list,
            "max_days": house.max_days,
            "min_days": house.min_days,
            "price": house.price,
            "room_count": house.room_count,
            "title": house.title,
            "unit": house.title,
            "user_avatar": str(user.avatar),
            "user_id": house.user,
            "user_name": user.real_name
        },
        "user_id": 1
    }

        return JsonResponse({
            'data':data,
            "errmsg": "OK",
            "errno": "0"
        })



'''接单和拒单'''

class AcceptRejcet(LoginRequiredMixin,View):
    def put(self,request,order_id):
        action = request.GET.get('action')
        reason = request.GET.get('reason')

        if not all(action):
            return http.HttpResponseForbidden('缺少必传参数')
        # 判断status是否合法
        try:
            order = Order.objects.get(status=int(action))
        except Exception:
            return http.HttpResponseForbidden('参数status错误')
        # 判断pay_method是否合法
        if int(action) not in [Order.ORDER_STATUS['WAIT_ACCEPT'],
                              Order.ORDER_STATUS['REJECTED']]:
            return http.HttpResponseForbidden('参数status错误')

        # 获取登录用户
        user = request.user

        if action is Order.ORDER_STATUS['WAIT_ACCEPT']:
            order = Order.objects.create(
                order_id = order_id,
                user = user,
                begin_date = order.begin_date,
                end_date = order.end_date,
                days = order.end_date - order.begin_date,
                house_price = order.house_price,
                amount = order.house_price * (order.end_date - order.begin_date),
                status = Order.ORDER_STATUS['WAIT_ACCEPT'],
                comment = order.comment)

        else:
            status = Order.ORDER_STATUS['REJECTED']
            order.comment.append(reason)
            order.save()

        return JsonResponse({
                    "errno": "0",
                    "errmsg": "操作成功"
                    })
